package com.lnj.config;

import dev.langchain4j.mcp.McpToolProvider;
import dev.langchain4j.mcp.client.DefaultMcpClient;
import dev.langchain4j.mcp.client.McpClient;
import dev.langchain4j.mcp.client.transport.McpTransport;
import dev.langchain4j.mcp.client.transport.stdio.StdioMcpTransport;
import dev.langchain4j.service.tool.ToolProvider;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * MCP 工具运行的原理: 每个 MCP 工具本质上是一个可以从命令行启动的 Node.js 程序，例如：npx -y tavily-mcp@0.2.2
 */


@Configuration
public class McpToolConfig {

    String Tavily_API_Key="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";

    @Bean
    public ToolProvider toolProvider() {
        // === 构建 Tavily 工具 ===
        McpClient tavilyClient = buildMcpClient(
                "tavily-mcp@0.2.2",
                Map.of("TAVILY_API_KEY", Tavily_API_Key)
        );


        // === 注册到 ToolProvider 中 ===
        return McpToolProvider.builder()
                .mcpClients(List.of(tavilyClient))
                .build();
    }

    //为每个 MCP 工具包创建一个可调用的 McpClient 实例。
    private McpClient buildMcpClient(String mcpPackage, Map<String, String> environment) {
        McpTransport transport = new StdioMcpTransport.Builder()
                .command(Arrays.asList("D:\\nodejs\\npx.cmd", "-y", mcpPackage))
                .environment(environment)
                .logEvents(true)
                .build();

        return new DefaultMcpClient.Builder()
                .transport(transport)
                .build();
    }
}

